import { defineStore, storeToRefs } from 'pinia';
import Cookies from 'js-cookie';
import { getSettingStore, useSettingStore } from '~/store/modules/setting.ts';
import router from '~/router';
import { AjaxResponseWrapper, APP_TOKEN } from '~/common/index.ts';
import { LoginInfo } from '~/model/login';
import { parseAjaxResponse, ResponseOptions } from '~/common/request.ts';
import { login } from '~/api/userApi.ts';

const appCookieName = '_sn_token_';

export const useUserStore = defineStore('user', {
  state: () => ({
    name: '',
    age: 0,
    sex: '',
    token: Cookies.get(appCookieName) || ''
  }),
  actions: {
    changeName(name: string) {
      this.$patch({
        name
      });
    },
    changeAge(age: number) {
      this.age = age;
      this.sex = '男';
    },
    setToken(token: string) {
      this.token = token;
      Cookies.set(appCookieName, token);
    },
    getToken() {
      return Cookies.get(appCookieName);
    },
    removeToken() {
      this.token = '';
      Cookies.remove(appCookieName);
    },
    // 用户是否认证
    isAuthenticated(): boolean {
      return !!this.token;
    },
    login: function (account: string, password: string): Promise<AjaxResponseWrapper<LoginInfo>> {
      let { clientId } = getSettingStore();
      return new Promise((resolve, reject) => {
        login({
          account,
          password,
          clientId: clientId.value
        })
          .then(res => {
            let options: ResponseOptions = {
              data: res,
              onSuccess: () => {
                let extras = res.extras || {};
                let token = extras[APP_TOKEN];
                this.setToken(token);
                resolve(res);
              },
              onFailure: () => {
                resolve(res);
              },
              showSuccessMessage: false,
              showErrorMessage: false
            };
            parseAjaxResponse(options);
          })
          .catch(error => {
            reject(error);
          });
      });
    },
    logout() {
      this.removeToken();
      useSettingStore().resetAsideMenu();
      useSettingStore().$reset();
      router.push('/login');
    }
  }
});

export function getUserStore() {
  return storeToRefs(useUserStore());
}
